#! /bin/sh

abs_top_builddir='@abs_top_builddir@'
wrap_program=`basename '@wrap_program@'`

# Strip the first directory from $PATH that contains $wrap_program,
# so that below we run the real $wrap_program, not ourselves.
not_found=true
new_path=
first=true
save_IFS=$IFS
IFS=:
for dir in $PATH; do
    IFS=$save_IFS
    if $not_found && test -x "$dir/$wrap_program"; then
        not_found=false
    else
        if $first; then
            first=false
            new_path=$dir
        else
            new_path=$new_path:$dir
        fi
    fi
done
IFS=$save_IFS
if $not_found; then
    echo "$0: error: cannot find $wrap_program in \$PATH" >&2
    exit 1
fi
PATH=$new_path
export PATH

if test "$DISABLE_LCOV" = true; then
    exec $wrap_program "$@"
    exit 1
fi

# XXX Probably want some kind of synchronization here to deal with
# programs running in parallel.
LCOV="lcov -b $abs_top_builddir -d $abs_top_builddir -q"
$LCOV -z

# Run the subprocess and propagate signals to it.
for signal in 1 2 3 5 15; do
    trap "kill -$signal \$!     # Propagate signal
          trap - $signal        # Reset signal to default
          wait                  # Wait for child to die
          kill -$signal $$      # Kill ourselves with same signal
          exit 1                # Exit in case 'kill' failed" $signal
done
$wrap_program 0<&0 "$@" &       # 0<&0 prevents shell from closing stdin
exec 0</dev/null                # Don't hold stdin open unnecessarily
wait $!; rc=$?

# Run lcov, but only if some .gcda files were produced, since lcov
# complains otherwise.
for file in `find "$abs_top_builddir" -name '*.gcda'`; do
    $LCOV -c -o - >> "$abs_top_builddir/tests/coverage.info"
    break
done

exit $rc
